/*
 * @Author: chaoxiaoshu-mx leukotrichia@163.com
 * @Date: 2023-02-09 16:58:12
 * @LastEditors: chaoxiaoshu-mx leukotrichia@163.com
 * @LastEditTime: 2023-02-10 10:24:19
 * @FilePath: \vue-remote-component\vue-main\src\utils\vm.js
 * @Description: 
 */
import TP from "../api/TP"
/**
 * 将字符串转换成代码对象
 * @param code 代码
 * @param value 默认值
 * @param params scoped变量，上下文变量，类似全局变量
 */
export function stringToCode(code, value, params) {
  const result = { value, error: null }
  try {
    result.value = new Function('context', `return ${code}`)(params) || value // eslint-disable-line no-new-func
  } catch (e) {
    console.error('js脚本错误：', e)
    result.error = e
  }

  return result
}

/**
 * 执行一段字符串格式的函数
 */
export function runFnInVm(code, params, globalParams) {
  const NOOP = args => args
  const result = stringToCode(code, NOOP, globalParams)
  const fn = result.value
  result.value = params
  if (result.error) {
    return result
  }
  if (typeof fn !== 'function') {
    console.error('非法的js脚本函数', fn)
    result.error = new Error('非法的js脚本函数')
    return result
  }
  try {
    result.value = fn.call(fn, params)
  } catch (e) {
    console.error('js脚本执行错误：', e)
    result.error = e
  }
  return result
}

/**
 * @description: 解析vue文件，拆分成template/js/css代码
 * @param {*} str
 * @return {*}
 */
export function deconstruction(str) {
  const code = (str || "");
  // template
  const tempMatch = code.match(/<template>([\s\S]*?)<\/template>/);
  let template = (tempMatch ? tempMatch[1] : code).trim();

  // js
  const jsMatch = code.match(/<script[\s\S]*?>([\s\S]*?)<\/script>/);
  let jsCode = jsMatch ? jsMatch[1] : code;
  const exMatch = jsCode.match(/export([\s\S]*?)default/);
  exMatch && (jsCode = jsCode.replace(exMatch[0], "").trim());
  let js = "function generate() {\n";
  js += "const TP = this.$TP;"
  js += "return " + jsCode + "\n}" 

  // css
  const cssMatch = code.match(/<style[\s\S]*?>[\s\S]*?<\/style>/);
  let css = (cssMatch ? cssMatch[1] : code).trim();

  return { template, js, css };

}
